#include "GeoBox.h"

GeoBox::GeoBox(float mWidth, float mHeight, float mDepth, int mWSegment, int mHSegment, int mDSegment)
	: Geometry(), m_width(mWidth), m_height(mHeight),
	  m_wSegment(mWSegment),
	  m_hSegment(mHSegment), m_depth(mDepth), m_dSegment(mDSegment)
{
	makeData();
}

void GeoBox::makeData()
{

	Vertices vertices;
	Indices indices;
	// x y z
	makePlane(vertices, indices, 0, 1, 2, 1, m_width, m_height, m_depth, m_wSegment, m_hSegment);
	makePlane(vertices, indices, 0, 1, 2, -1, m_width, m_height, -m_depth, m_wSegment, m_hSegment);
	// y z x
	makePlane(vertices, indices, 1, 2, 0, 1, m_height, m_depth, m_width, m_hSegment, m_dSegment);
	makePlane(vertices, indices, 1, 2, 0, -1, m_height, m_depth, -m_width, m_hSegment, m_dSegment);
	// z x y
	makePlane(vertices, indices, 2, 0, 1, 1, m_depth, m_width, m_height, m_dSegment, m_wSegment);
	makePlane(vertices, indices, 2, 0, 1, -1, m_depth, m_width, -m_height, m_dSegment, m_wSegment);

	setup(vertices, indices);
}

void GeoBox::makePlane(Vertices &vertices, Indices &indices, int u, int v, int w, int dir, float width, float height, float depth, int wSegment,
					   int hSegment)
{
	float w_half = width / 2.0;
	float h_half = height / 2.0;
	float d_half = depth / 2.0;
	float dx = width / wSegment;
	float dy = height / hSegment;
	auto offset = vertices.size();
	//计算顶点坐标和纹理坐标
	for (int iy = 0; iy <= hSegment; ++iy)
	{
		float vy = iy * dy - h_half;
		float ty = 1 - static_cast<float>(iy) / hSegment;
		for (int ix = 0; ix <= wSegment; ++ix)
		{
			float vx = ix * dx - w_half;
			float tx = static_cast<float>(ix) / wSegment;
			glm::vec3 vec;
			vec[u] = vx * dir;
			vec[v] = vy * dir;
			vec[w] = d_half;
			vertices.push_back({vec, {tx, ty}});
		}
	}
	//计算索引
	for (unsigned int iy = 0; iy < hSegment; ++iy)
		for (unsigned int ix = 0; ix < wSegment; ++ix)
		{
			unsigned int a = offset + iy * (wSegment + 1) + ix;
			unsigned int b = a + 1;
			unsigned int c = offset + (iy + 1) * (wSegment + 1) + ix;
			unsigned int d = c + 1;
			indices.push_back(a);
			indices.push_back(c);
			indices.push_back(d);
			indices.push_back(a);
			indices.push_back(b);
			indices.push_back(d);
		}
}
